package cn.itcast.bos.service.take_delivery.impl;

import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.update.UpdateHelper.Operation;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.take_delivery.WayBillRepository;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.index.WayBillIndexRepository;
import cn.itcast.bos.service.take_delivery.WayBillService;

@Service
@Transactional
public class WayBillServiceImpl implements WayBillService {

	@Autowired
	private WayBillRepository wayBillRepository;

	@Autowired
	private WayBillIndexRepository wayBillIndexRepository;

	// 运单分页查询
	@Override
	public Page<WayBill> pageQuery(WayBill model, Pageable pageable) {
		// 判断model中的条件是否存在,如果四个条件全部为空,则直接从数据库中查询
		if (StringUtils.isBlank(model.getWayBillNum()) &&
				StringUtils.isBlank(model.getSendAddress()) &&
				StringUtils.isBlank(model.getRecAddress()) &&
				StringUtils.isBlank(model.getSendProNum()) &&
				(model.getSignStatus() == null || model.getSignStatus() == 0)) {
			// 此时直接从数据库中查询,也可以不写此逻辑,全部从索引库中查询数据,因为项目后期索引库和数据库中的运单数据要求是同步的
			Page<WayBill> page = wayBillRepository.findAll(pageable);
			return page;
		} else {
			// 查询条件
			// must 代表必须满足的条件 and
			// must no 代表条件必须不成立 not
			// should 代表条件可以成立 or
			// 创建以个布尔查询对象BoolQueryBuilder,可以封装多个查询条件
			BoolQueryBuilder query = new BoolQueryBuilder();

			// 向组合查询对象中添加查询条件
			if (StringUtils.isNotBlank(model.getWayBillNum())) {
				// 利用精准查询的方式封装运单号的查询
				QueryBuilder termQuery = new TermQueryBuilder("wayBillNum",
						model.getWayBillNum());

				query.must(termQuery);
			}

			if (StringUtils.isNotBlank(model.getSendAddress())) {
				// 利用模糊查询的方式封装寄件方地址
				// 利用模糊查询的方式会导致当输入的查询词条大于一个封装的词条时查询不到信息
				QueryBuilder wildcardQuery = new WildcardQueryBuilder("sendAddress",
						"*" + model.getSendAddress() + "*");

				// 增加一个分词查询对象
				QueryBuilder stringQuery = new QueryStringQueryBuilder(
						model.getSendAddress()).field("sendAddress")
								.defaultOperator((Operator.AND));

				// 这里利用布尔查询对象额外封装一个QueryStringQuery先分词条再查询的独享
				BoolQueryBuilder query1 = new BoolQueryBuilder();
				// 利用should进行封装,这两个查询条件时or来连接
				query1.should(stringQuery);
				query1.should(wildcardQuery);

				query.must(query1);
			}

			if (StringUtils.isNotBlank(model.getRecAddress())) {
				// 利用模糊查询的方式封装寄件方地址
				// 利用模糊查询的方式会导致当输入的查询词条大于一个封装的词条时查询不到信息
				QueryBuilder wildcardQuery = new WildcardQueryBuilder("recAddress",
						"*" + model.getRecAddress() + "*");
				// 增加一个分词查询对象
				QueryBuilder stringQuery = new QueryStringQueryBuilder(
						model.getRecAddress()).field("recAddress")
								.defaultOperator((Operator.AND));

				// 这里利用布尔查询对象额外封装一个QueryStringQuery先分词条再查询的独享
				BoolQueryBuilder query2 = new BoolQueryBuilder();
				// 利用should进行封装,这两个查询条件时or来连接
				query2.should(stringQuery);
				query2.should(wildcardQuery);

				query.must(query2);
			}

			if (StringUtils.isNotBlank(model.getSendProNum())) {
				// 利用精准查询的方式封装运单号的查询
				QueryBuilder termQuery = new TermQueryBuilder("sendProNum",
						model.getSendProNum());
				query.must(termQuery);
			}

			if (model.getSignStatus() != null || model.getSignStatus() != 0) {
				// 签收状态查询
				QueryBuilder termQuery = new TermQueryBuilder("signStatus",
						model.getSignStatus());
				query.must(termQuery);
			}

			// 这里是为了最后进行查询获得的是一个Page对象
			SearchQuery searchQuery = new NativeSearchQuery(query);
			// 封装分页查询的条件pageable
			searchQuery.setPageable(pageable);

			// 调取分页查询的Dao从索引库中进行查询
			Page<WayBill> page = wayBillIndexRepository.search(searchQuery);
			return page;
		}
	}

	// 运单保存
	@Override
	public void save(WayBill model) {
		// 对数据库中数据是保存还是更新是看主键是否已经存在,而非看订单号
		// 根据运单号查询到运单
		WayBill persistWayBill = wayBillRepository
				.findByWayBillNum(model.getWayBillNum());
		// 判断运单对象
		if (persistWayBill == null) {
			// 订单不存在,保存到数据库
			wayBillRepository.save(model);
			// 同时保存到索引库
			wayBillIndexRepository.save(model);
		} else {
			// 订单已经存在,执行的是更新的操作--主要是将model的内容添加上Id,通过持久化对象自动更新到数据库
			try {
				// 判断订单状态是否为待发货
				if (persistWayBill.getSignStatus() == 1) {
					Integer id = persistWayBill.getId();
					// 将model中的属性值赋值到persistWayBill中
					BeanUtils.copyProperties(persistWayBill, model);
					// 为persistWayBill设置id使其成为持久化对象
					persistWayBill.setId(id);
					// 保存到索引库
					wayBillIndexRepository.save(persistWayBill);
				} else {
					// 运单状态已经运输中,不能修改
					throw new RuntimeException("运单已发出,无法修改保存!");
				}

			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		}
	}

	// 添加索引同步的方法,可以利用Quartz定时调用保证数据库和索引库的数据一致性
	public void syncIndex() {
		// 查询数据库
		List<WayBill> wayBills = wayBillRepository.findAll();
		// 同步到索引库中
		wayBillIndexRepository.save(wayBills);
	}

	// 快速运单号查询对应运单对象
	@Override
	public WayBill findByWayBillNum(String wayBillNum) {
		WayBill wayBill = wayBillRepository.findByWayBillNum(wayBillNum);
		return wayBill;
	}

	@Override
	public List<WayBill> findWayBills(WayBill wayBill) {
		// 判断WayBill 中条件是否存在
		if (StringUtils.isBlank(wayBill.getWayBillNum())
				&& StringUtils.isBlank(wayBill.getSendAddress())
				&& StringUtils.isBlank(wayBill.getRecAddress())
				&& StringUtils.isBlank(wayBill.getSendProNum())
				&& (wayBill.getSignStatus() == null || wayBill.getSignStatus() == 0)) {
			// 无条件查询 、查询数据库
			return wayBillRepository.findAll();
		} else {
			// 查询条件
			// must 条件必须成立 and
			// must not 条件必须不成立 not
			// should 条件可以成立 or
			BoolQueryBuilder query = new BoolQueryBuilder(); // 布尔查询 ，多条件组合查询
			// 向组合查询对象添加条件
			if (StringUtils.isNotBlank(wayBill.getWayBillNum())) {
				// 运单号查询
				QueryBuilder tempQuery = new TermQueryBuilder("wayBillNum",
						wayBill.getWayBillNum());
				query.must(tempQuery);
			}
			if (StringUtils.isNotBlank(wayBill.getSendAddress())) {
				// 发货地 模糊查询
				// 情况一： 输入"北" 是查询词条一部分， 使用模糊匹配词条查询
				QueryBuilder wildcardQuery = new WildcardQueryBuilder(
						"sendAddress", "*" + wayBill.getSendAddress() + "*");

				// 情况二： 输入"北京市海淀区" 是多个词条组合，进行分词后 每个词条匹配查询
				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(
						wayBill.getSendAddress()).field("sendAddress")
								.defaultOperator(Operator.AND);

				// 两种情况取or关系
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardQuery);
				boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder);
			}
			if (StringUtils.isNotBlank(wayBill.getRecAddress())) {
				// 收货地 模糊查询
				QueryBuilder wildcardQuery = new WildcardQueryBuilder(
						"recAddress", "*" + wayBill.getRecAddress() + "*");
				query.must(wildcardQuery);
			}
			if (StringUtils.isNotBlank(wayBill.getSendProNum())) {
				// 速运类型 等值查询
				// QueryBuilder termQuery = new TermQueryBuilder("sendProNum",
				// wayBill.getSendProNum());
				// query.must(termQuery);

				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(
						wayBill.getSendProNum())
								.field("sendProNum").defaultOperator(Operator.AND);
				query.must(queryStringQueryBuilder);
			}
			if (wayBill.getSignStatus() != null && wayBill.getSignStatus() != 0) {
				// 签收状态查询
				QueryBuilder termQuery = new TermQueryBuilder("signStatus",
						wayBill.getSignStatus());
				query.must(termQuery);
			}

			SearchQuery searchQuery = new NativeSearchQuery(query);
			// ElasticSearch 允许搜索分页查询，最大数据条数10000
			Pageable pageable = new PageRequest(0, 10000); //利用分页来查询所有(尽量多)的信息,是为了调用setPageable方法返回一个List集合
			searchQuery.setPageable(pageable); // 分页效果
			
			// 有条件查询 、查询索引库
			return wayBillIndexRepository.search(searchQuery).getContent();
		}
	}

}
